package com.sikulifang.bank.simulation.server.handler;

import com.sikulifang.bank.simulation.persistence.Bank;
import com.sikulifang.bank.simulation.service.MessageService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.nio.charset.StandardCharsets;

/**
 * 将zabbix的主动模式数据发送至运管-zabbix server
 *
 * @author zhoul
 * @since 2.0.0
 */
@Slf4j
public class SocketHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Getter
    private final ApplicationContext applicationContext;
    @Setter
    @Getter
    private Bank bank;

    public SocketHandler(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
        String data = msg.toString(StandardCharsets.UTF_8);
        String sessionId = ctx.channel().id().asLongText();
        try {
            System.out.println("sessionId---------->" + sessionId);

            MessageService bankService = getApplicationContext().getBean(MessageService.class);
            byte[] resultBytes = bankService.handleMessage(bank, data);
            // byte[] bytes = "aaa".getBytes("GBK");
            ctx.writeAndFlush(Unpooled.copiedBuffer(resultBytes));
        } catch (Exception e) {
            log.error(">>> request error :", e);
        } finally {
            ctx.close();
        }
    }
}
